package com.thatvn.diemtinvietnam;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.Html;
import android.util.Log;
import android.util.Xml.Encoding;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebViewClient;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Dialog;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.Thread;

import android.content.SharedPreferences;
import android.preference.*;

import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdSize;
import com.google.android.gms.ads.AdView;
import com.thatvn.diemtinvietnam.viewWeb.myWebClient;
//import com.example.diemtinvietnam.viewWeb.showNewsFromUrlTask;
import com.thatvn.diemtinvietnam.R;

//import com.example.diemtinvietnam.jsonParseDetail;
//import com.example.diemtinvietnam.viewWeb;
//import com.example.diemtinvietnam.viewWeb.myWebClient;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;

public class viewWeb extends Activity {
	public String urlGetDetailNews = Config.domain+"/comment/mReadNews/";//Config.domain+"/Title/getFullcontent?id=";
	// "http://diemtinvietnam.vn/comment/mReadNews/";//"http://diemtinvietnam.vn/Title/getFullcontent?id=";
	private Thread thread;
	private Boolean loadingFinished = false;
	private Boolean redirect = false;
	private jsonParseDetail jsonP;
	private TextView title;
	private TextView des;
	private WebView fullContent;
	private WebSettings fullContentsettings;
	private ProgressDialog dialog;
	private String detailLink = "";
	private String link = "";
	private String idNews = "";
	private String hasContent = "0";
	private String DATA_STRING = "";
	private AdView adView;
	private static final String AD_UNIT_ID = "ca-app-pub-6575239088642506/9081815672";
	private AlertDialog alertDialog;
	public int maxDelay = 20000;
	public long oldTime = 0;
	public boolean loading = true;
	public boolean is_Single_Colunm=true;
	private ActionBar actionBar;
	private Context context;
	private int maxSdk=19;
	ProgressBar Pbar;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_detail);
		actionBar = getActionBar();
		actionBar.setBackgroundDrawable(getResources().getDrawable(
				R.drawable.bg));
		context = this.context;
		// Log.e("viewWeb","ok1");
		Intent intent = getIntent();
		// Log.e("viewWeb","ok2");
		link = intent.getStringExtra("link");
		Log.e("viewWeb","ok3, link="+link);
		idNews = intent.getStringExtra("id");
		hasContent = intent.getStringExtra("hasContent");
		if (hasContent.equals("1")) {// && (link.contains("laodong") ||
										// link.contains("vietbao") ||
										// link.contains("hanoimoi"))
			detailLink = urlGetDetailNews + idNews;
		} else {
			detailLink = link;
		}
		//detailLink="http://diemtinvietnam.vn/OChu/Play";
		// title = (TextView) findViewById(R.id.titleDetail);
		Log.e("viewWeb","ok4");
		// des = (TextView) findViewById(R.id.desDetail);
		// Log.e("viewWeb","ok5");
		Pbar = (ProgressBar) findViewById(R.id.pB1);
		////Pbar.setMessage(Config.processMessage);
		//Pbar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		//Pbar.setProgress(0);
		//Pbar.setMax(100);
		fullContent = (WebView) findViewById(R.id.webview);
		fullContent.getSettings().setLoadWithOverviewMode(true);
		if (Build.VERSION.SDK_INT<maxSdk){
			fullContent.getSettings().setLayoutAlgorithm(
					LayoutAlgorithm.NARROW_COLUMNS);
		}
//		}else{
//			fullContent.getSettings().setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
//		}
		Log.e("AndroidVersion", String.valueOf(Build.VERSION.SDK_INT));
		is_Single_Colunm=false;
		fullContent.getSettings().setUseWideViewPort(true);
		//fullContent.setWebContentsDebuggingEnabled(true);
		// .setUseWideViewPort(true);
		
		fullContent.getSettings().setPluginState(WebSettings.PluginState.ON);
		//fullContent.getSettings().setPluginState(WebSettings.PluginState.ON_DEMAND);
		fullContent.getSettings().setBuiltInZoomControls(true);
		// fullContent.getSettings().setPluginState(PluginState.ON);
		fullContent.setWebViewClient(new myWebClient());
		//if (Build.VERSION.SDK_INT<maxSdk){
			fullContent.setWebChromeClient(new WebChromeClient() {
	            public void onProgressChanged(WebView view, int progress) 
	            {
	            if(progress < 100 && Pbar.getVisibility() == ProgressBar.GONE){
	                Pbar.setVisibility(ProgressBar.VISIBLE);
	                //txtview.setVisibility(View.VISIBLE);
	            }
	            Pbar.setProgress(progress);
	            if(progress == 100) {
	                Pbar.setVisibility(ProgressBar.GONE);
	                //txtview.setVisibility(View.GONE);
	            }
	         }
			});
		//}
		Log.e("onCreate", "ok3");
//		if (hasContent.equals("1")){
//			fullContent.getSettings().setJavaScriptEnabled(false);
//		}else{
			fullContent.getSettings().setJavaScriptEnabled(true);
//		}
		fullContentsettings=fullContent.getSettings();
		// MyJavaScriptInterface MI=new MyJavaScriptInterface();
		// fullContent.addJavascriptInterface(MI, "HTMLOUT");

		// dialog = ProgressDialog.show(this,
		// Config.processInfo,Config.processMessage, true);
		if (Build.VERSION.SDK_INT<maxSdk){
			new showNewsFromUrlTask().execute(detailLink);
		}
		else
		{
			fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL);
			fullContent.loadUrl(detailLink);
		}
		adView = new AdView(this);
		adView.setAdSize(AdSize.BANNER);
		adView.setAdUnitId(AD_UNIT_ID);
		RelativeLayout rl = new RelativeLayout(this);
		RelativeLayout.LayoutParams lay = new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.FILL_PARENT,
				RelativeLayout.LayoutParams.WRAP_CONTENT);
		lay.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.layoutWeb);
		layout.addView(adView, lay);
		AdRequest adRequest = new AdRequest.Builder().build();
		adView.loadAd(adRequest);
	}

	private class showNewsFromUrlTask extends AsyncTask<String, Void, String> {
		@Override
		protected String doInBackground(String... urls) {
			// params comes from the execute() call: params[0] is the url.
			int type = 0;
			try {
				String data = "";
				Log.e("doInBackground", "ok11111111111");
				// if(hasContent.equals("1")){
				// Log.e("doInBackground", "22222");
				// data=readFile(idNews+".html");
				// //Log.e("doInBackground", "data============"+data);
				// if (data.equals(""))
				// {
				// Log.e("Khong doc duoc file", "not ok");
				// data=Utils.getWebContent(urls[0]);
				// type=2;
				// }
				// else {
				// Log.e("Lay ra duong dan file thanh cong", "ok");
				// type=1;
				// }
				// Log.e("doInBackground", "555555");
				// }
				// Log.e("doInBackground", "6666");
				//
				// Log.e("onCreate", "ok4");
				// if(!data.equals("")){
				// //if (type==2){
				// fullContent.loadData(data, "text/html; charset=UTF-8", null);
				// // }else{
				// // fullContent.loadDataWithBaseURL(null, data, mimeType,
				// encoding, historyUrl);
				// // }
				// Log.e("OKOKOKOKOKOKOKOKOKOKOKOOKOKOKOKOKOKOKO", "ok");
				// }else
				// {
				// fullContent.loadUrl(urls[0]);
				// Log.e("Not OK", "ok");
				// }
				// int duration=Toast.LENGTH_SHORT;
				// Toast toast = Toast.makeText(context, "Loading...",duration);
				// toast.show();
				fullContent.loadUrl(urls[0]);
				Log.e("doInBackground", "77777");
				return "1";
			} catch (Exception e) {
				Log.e("showNewsFromUrlTask", "can not download");
				// dialog.dismiss();
				showExtProgram(Config.alertInfo, Config.alertMessage);
				// ResultDownloadWebpage=0;
				return "0";
			}
		}

		// onPostExecute displays the results of the AsyncTask.
		@Override
		protected void onPostExecute(String result) {
			// textView.setText(result);
			// try{
			// if(dialog!=null) dialog.dismiss();
			// }catch(Exception ex){

			// }
			if (result.equals("0")) {
				Log.e("onPostExecute", "can not download");
				showExtProgram(Config.alertInfo, Config.alertMessage);
			} else {
				Log.e("onPostExecute", "ok");
				// Caching
				// if (!result.equals("")){
				// writeFile(idNews+".html",result);
				// Log.e("Caching thanh cong", "ok");
				// }
			}
			// try{
			// if(dialog!=null) dialog.dismiss();
			// }catch(Exception ex){

			// }
		}
	}

	public void writeFile(String filename, String content) {
		if (isExternalStorageWritable()) {
			File root = android.os.Environment.getExternalStorageDirectory();
			// tv.append("\nExternal file system root: "+root);

			// See
			// http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder

			File dir = new File(root.getAbsolutePath() + "/DiemTinVietNam/");
			dir.mkdirs();
			File file = new File(dir, filename);
			try {
				FileOutputStream f = new FileOutputStream(file);
				PrintWriter pw = new PrintWriter(f);
				pw.println(content);
				pw.flush();
				pw.close();
				f.close();
			} catch (FileNotFoundException e) {
				// e.printStackTrace();
				Log.e("Error",
						"******* File not found. Did you"
								+ " add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public String readFile(String filename) {
		Log.e("isExternalStorageReadable()==",
				String.valueOf(isExternalStorageReadable()));
		if (!isExternalStorageReadable())
			return "";

		File sdcard = android.os.Environment.getExternalStorageDirectory();
		Log.e("readFile()==", sdcard.getAbsolutePath() + "/DiemTinVietNam/"
				+ filename);
		// Get the text file
		File file = new File(sdcard, sdcard.getAbsolutePath()
				+ "/DiemTinVietNam/" + filename);
		Log.e("readFile()==", String.valueOf(file.exists()));
		if (!file.exists())
			return "";// return sdcard.getAbsolutePath() +
						// "/DiemTinVietNam/"+filename;
		Log.e("readFile()==", sdcard.getAbsolutePath() + "/DiemTinVietNam/"
				+ filename);
		// Read text from file
		StringBuilder text = new StringBuilder();
		Log.e("readFile()==", "3333");
		try {
			BufferedReader br = new BufferedReader(new FileReader(file));
			String line;
			while ((line = br.readLine()) != null) {
				text.append(line);
				// text.append('\n');
			}
		} catch (IOException e) {
			// You'll need to add proper error handling here
			Log.e("readFile()==", "errro");
		}
		Log.e("readFile()==", "444444");
		// Log.e("isExternalStorageReadable()==",text.toString());
		return text.toString();
	}

	/* Checks if external storage is available for read and write */
	public boolean isExternalStorageWritable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)) {
			return true;
		}
		return false;
	}

	/* Checks if external storage is available to at least read */
	public boolean isExternalStorageReadable() {
		String state = Environment.getExternalStorageState();
		if (Environment.MEDIA_MOUNTED.equals(state)
				|| Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
			return true;
		}
		return false;
	}

	public void showExtProgram(String title, String message) {

		 AlertDialog.Builder builder = new AlertDialog.Builder(this);
		
		 // 2. Chain together various setter methods to set the dialog
		 //characteristics
		 builder.setMessage(message)
		 .setTitle(title)
		 .setCancelable(false)
		 .setPositiveButton("Thoát",new DialogInterface.OnClickListener() {
		 public void onClick(DialogInterface dialog,int id) {
			 // if this button is clicked, close
			 // current activity
			 //viewWeb.this.finish();
			 //System.exit(0);
			 }
		 });
		
		 // 3. Get the AlertDialog from create()
		 Log.e("alertDialog", "ok11111111111");
		 alertDialog= builder.create();
		 alertDialog.show();
		 Log.e("alertDialog", "222222222");
		// CharSequence text = "Hello toast!";
//		int duration = Toast.LENGTH_SHORT;
//		Toast toast = Toast.makeText(context, message, duration);
//		toast.show();

	}

	public class myWebClient extends WebViewClient {
		
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			// TODO Auto-generated method stub
			//Log.e("onPageStarted", "ok1");
			super.onPageStarted(view, url, favicon);
			//Log.e("onPageStarted", "ok2");
		}

		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			// TODO Auto-generated method stub
			//Log.e("shouldOverrideUrlLoading", "ok1");
			view.loadUrl(url);
			//Log.e("shouldOverrideUrlLoading", "ok2");
			return true;
		}

		@Override
		public void onPageFinished(WebView view, String url) {
			// TODO Auto-generated method stub
			//Log.e("onPageFinished", "ok1");
			super.onPageFinished(view, url);
			//Log.e("onPageFinished", "ok2");
			// progressBar.setVisibility(View.GONE);
			// loading=false;
			//dialog.dismiss();
			//Log.e("onPageFinished", "ok3");
			if (!Config.isTablet){
				if (Build.VERSION.SDK_INT<maxSdk){
					fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);  
				}
				fullContentsettings.setUseWideViewPort(false);
				//item.setIcon(R.drawable.full_screen);
				//item.setTitle("Phóng to ảnh");
				is_Single_Colunm=true;
			}
		}
		
		
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && fullContent.canGoBack()) {
			//this.finish();
			//viewWeb.this.finish();
	    	//System.exit(0);
			fullContent.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate menu resource file.
		// Log.e("aaaaaaaaaaaaaaaaa","onCreateOptionsMenu1");
		getMenuInflater().inflate(R.menu.menu_share, menu);
		// Log.e("aaaaaaaaaaaaaaaaa","onCreateOptionsMenu2");
		// Locate MenuItem with ShareActionProvider
		// MenuItem item = menu.findItem(R.id.menu_item_share);
		// Log.e("aaaaaaaaaaaaaaaaa","onCreateOptionsMenu3");
		// Fetch and store ShareActionProvider
		// mShareActionProvider = (ShareActionProvider)
		// item.getActionProvider();
		// Log.e("aaaaaaaaaaaaaaaaa","onCreateOptionsMenu4");
		// mShareActionProvider.setShareIntent(this.getIntent());
		// Return true to display menu
		return true;
		// return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Log.e("aaaaaaaaaaaaaaaaa",String.valueOf(item.getItemId()));
		switch (item.getItemId()) {
		case R.id.menu_item_share:
			// HomePage();
			// Log.e("aaaaaaaaaaaaaaaaa","1");
			String message = this.detailLink;
			Intent share = new Intent(Intent.ACTION_SEND);
			share.setType("text/plain");
			share.putExtra(Intent.EXTRA_TEXT, message);
			startActivity(Intent.createChooser(share, "Share link"));
			// Log.e("aaaaaaaaaaaaaaaaa","2");
			return true;
		case R.id.menu_item_back:
			//viewWeb.this.finish();
			//System.exit(0);
			this.finish();
			return true;
		case R.id.menu_item_increase_font:
    		//WebSettings fullContentsettings = fullContent.getSettings();
    		fullContentsettings.setTextZoom( (int)(fullContentsettings.getTextZoom() * 1.1) );
    		return true;
//		case R.id.menu_item_full_screen:
//    		//WebSettings fullContentsettings = fullContent.getSettings();
//			if (is_Single_Colunm){
//				if (Build.VERSION.SDK_INT<maxSdk){
//					fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.NARROW_COLUMNS);  
//				} else{
//					fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); 
//				}
//				fullContentsettings.setUseWideViewPort(true);
//				item.setIcon(R.drawable.normal_screen);
//				item.setTitle("Thu nhỏ ảnh");
//				is_Single_Colunm=false;
//    		}else{
//    			if (Build.VERSION.SDK_INT<maxSdk){
//    				fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN); 
//    			}else{
//					fullContentsettings.setLayoutAlgorithm(LayoutAlgorithm.NORMAL); 
//				}
//				fullContentsettings.setUseWideViewPort(false);
//				item.setIcon(R.drawable.full_screen);
//				item.setTitle("Phóng to ảnh");
//				is_Single_Colunm=true;
//    		}
//			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}
}
